#pragma once

#include "../stdafx.h"

class GameTimer
{
public:
	GameTimer() : m_secondsPerCount(0.0), m_deltaTime(-1.0), m_baseTime(0),
		m_pausedTime(0), m_prevTime(0), m_currTime(0), m_stopTime(0), m_stopped(false)
	{
		__int64 countsPerSec;
		QueryPerformanceFrequency((LARGE_INTEGER*)&countsPerSec);
		m_secondsPerCount = 1.0 / (double)countsPerSec;
	}
	float TotalTime() const
	{
		if (m_stopped)
			return static_cast<float>((m_stopTime - m_pausedTime - m_baseTime) * m_secondsPerCount);
		else
			return static_cast<float>((m_currTime - m_pausedTime - m_baseTime) * m_secondsPerCount);
	}
	float DeltaTime() const { return static_cast<float>(m_deltaTime); }
	void Reset()
	{
		__int64 currTime;
		QueryPerformanceCounter((LARGE_INTEGER*)&currTime);
		m_baseTime = m_prevTime = currTime;
		m_stopTime = 0;
		m_stopped = false;
	}
	void Start()
	{
		__int64 startTime;
		QueryPerformanceCounter((LARGE_INTEGER*)&startTime);
		if (m_stopped)
		{
			m_pausedTime += startTime - m_stopTime;
			m_prevTime = startTime;
			m_stopTime = 0;
			m_stopped = false;
		}
	}
	void Stop() // pause
	{
		if (!m_stopped)
		{
			__int64 currTime;
			QueryPerformanceCounter((LARGE_INTEGER*)&currTime);
			m_stopTime = currTime;
			m_stopped = true;
		}
	}
	void Tick() // call every frame
	{
		if (m_stopped)
		{
			m_deltaTime = 0.0;
			return;
		}
		__int64 currTime;
		QueryPerformanceCounter((LARGE_INTEGER*)&currTime);
		m_currTime = currTime;
		m_deltaTime = (m_currTime - m_prevTime) * m_secondsPerCount;
		m_prevTime = m_currTime;

		if (m_deltaTime < 0.0)
			m_deltaTime = 0.0;
	}


private:
	double m_secondsPerCount;
	double m_deltaTime;

	__int64 m_baseTime;
	__int64 m_pausedTime;
	__int64 m_stopTime;
	__int64 m_prevTime;
	__int64 m_currTime;

	bool m_stopped;
};

